package implementation {
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.geom.Rectangle;
import flash.utils.Timer;

import implementation.menu.MenuEncapsulation;

import palf.Gallery;

[SWF(width = 640, height = 480)]
public class Main extends Sprite {

	private var gallery : Gallery;

	public function Main() {
		createGallery();
		createMenu();
	}

	private function createGallery() : void {
		var item_container : Sprite = createItemContainer();
		gallery = new GalleryImplementation(item_container);
		item_container.addEventListener(MouseEvent.MOUSE_DOWN, onGalleryClick);
		this.addChild(item_container);

		var timer : Timer = new Timer(2000, 0);
		timer.addEventListener(TimerEvent.TIMER, onGalleryTimer);
		timer.start();
	}

	private function createMenu() : void {
		var menu_container : Sprite = createMenuContainer();
		var menu : MenuEncapsulation = new MenuEncapsulation();
		menu.init(menu_container, gallery);
		this.addChild(menu_container);
	}

	private function onGalleryClick(event : MouseEvent) : void {
		var target : DisplayObject = DisplayObject(event.target);
		gallery.selectItem(target);
	}

	private function onGalleryTimer(event : TimerEvent) : void {
		gallery.selectIndex(gallery.index + 1);
	}

	private function createItemContainer() : Sprite {
		const BOUNDS : Rectangle = new Rectangle(40, 40, 400, 400);
		var item_container : Sprite = new Sprite();
		item_container.graphics.lineStyle(2, 0x333333, 0.6);
		item_container.graphics.drawRoundRect(BOUNDS.x, BOUNDS.y, BOUNDS.width, BOUNDS.height, 16);
		item_container.graphics.moveTo(BOUNDS.x + BOUNDS.width / 2, BOUNDS.y);
		item_container.graphics.lineTo(BOUNDS.x + BOUNDS.width / 2, BOUNDS.y + BOUNDS.height);
		item_container.graphics.moveTo(BOUNDS.x, BOUNDS.y + BOUNDS.height / 2);
		item_container.graphics.lineTo(BOUNDS.x + BOUNDS.width, BOUNDS.y + BOUNDS.height / 2);
		populateContainerWithItems(item_container);
		return item_container;
	}

	private function populateContainerWithItems(item_container : Sprite) : void {
		var item : Sprite;
		for (var i : uint = 0; i < 16; i++) {
			item = new TestItem((i + 1).toString());
			item.x = 240;
			item.y = 240;
			item_container.addChild(item);
		}
	}

	private function createMenuContainer() : Sprite {
		var menu_container : Sprite = new Sprite();
		menu_container.graphics.beginFill(0xbbbbbb);
		menu_container.graphics.drawRect(0, 0, 160, 480);
		menu_container.graphics.endFill();
		menu_container.x = 640 - menu_container.width;
		return menu_container;
	}

}
}
